<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="评价计划" prop="planId">
        <el-select v-model="formData.planId" placeholder="请选择评价计划" clearable>
          <el-option
            v-for="plan in planList"
            :key="plan.id"
            :label="plan.planName"
            :value="plan.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="科目名称" prop="subjectName">
        <el-input v-model="formData.subjectName" placeholder="请输入科目名称" />
      </el-form-item>

      <el-form-item label="科目代码" prop="subjectCode">
        <el-input v-model="formData.subjectCode" placeholder="请输入科目代码" />
      </el-form-item>
      
      <el-form-item label="科目类型" prop="subjectType">
        <el-select v-model="formData.subjectType" placeholder="请选择科目类型" @change="handleSubjectTypeChange">
          <el-option label="理论知识" value="theory" />
          <el-option label="技能操作" value="practical" />
          <el-option label="综合评价" value="comprehensive" />
        </el-select>
      </el-form-item>

      <el-form-item label="科目权重" prop="subjectWeight">
        <el-input-number
          v-model="formData.subjectWeight"
          :min="0"
          :max="1"
          :step="0.01"
          :precision="2"
          :disabled="formData.subjectType !== 'comprehensive'"
          placeholder="请输入科目权重"
        />
        <span style="margin-left: 8px; color: #909399;">
          = {{ (formData.subjectWeight * 100).toFixed(1) }}%
        </span>
        <div v-if="formData.subjectType !== 'comprehensive'" style="margin-top: 4px; color: #909399; font-size: 12px;">
          权重比例仅在综合评价类型下可用
        </div>
        <div v-else style="margin-top: 4px; color: #909399; font-size: 12px;">
          请输入0-1之间的小数，如0.5表示50%
        </div>
      </el-form-item>
      
      <el-form-item label="考试时长" prop="examDuration">
        <el-input-number
          v-model="formData.examDuration"
          :min="30"
          :max="480"
          placeholder="请输入考试时长"
        />
        <span style="margin-left: 8px; color: #909399;">分钟</span>
      </el-form-item>

      <el-form-item label="考试地点" prop="examLocation">
        <el-input
          v-model="formData.examLocation"
          placeholder="请输入考试地点"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="科目描述" prop="subjectDescription">
        <el-input
          v-model="formData.subjectDescription"
          type="textarea"
          :rows="3"
          placeholder="请输入科目描述"
        />
      </el-form-item>
      
      <el-form-item label="合格分数" prop="passingScore">
        <el-input-number
          v-model="formData.passingScore"
          :min="0"
          :max="formData.maxScore || 999.99"
          :precision="2"
          placeholder="请输入合格分数"
        />
        <span style="margin-left: 8px; color: #909399;">分</span>
      </el-form-item>

      <el-form-item label="满分" prop="maxScore">
        <el-input-number
          v-model="formData.maxScore"
          :min="0.01"
          :max="999.99"
          :precision="2"
          placeholder="请输入满分"
        />
        <span style="margin-left: 8px; color: #909399;">分</span>
      </el-form-item>
      


    </el-form>
    
    <template #footer>
      <el-button @click="submitForm" type="primary" :loading="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getSubject, createSubject, updateSubject } from '@/api/eval/subject'
import { getPlanListByStatus, getPlanPage } from '@/api/eval/plan'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const dialogTitle = computed(() => (formData.value.id ? '修改评价科目' : '添加评价科目'))
const formLoading = ref(false)
const formRef = ref()
const planList = ref<any[]>([])
const formData = ref({
  id: undefined,
  planId: undefined,
  subjectName: '',
  subjectCode: '',
  subjectType: 'theory',
  subjectWeight: 1.0,
  passingScore: 60.0,
  maxScore: 100.0,
  examDuration: 120,
  examLocation: '',
  subjectDescription: ''
})
const formRules = ref({
  planId: [{ required: true, message: '评价计划不能为空', trigger: 'change' }],
  subjectName: [
    { required: true, message: '科目名称不能为空', trigger: 'blur' },
    { max: 100, message: '科目名称长度不能超过100个字符', trigger: 'blur' }
  ],
  subjectCode: [
    { required: true, message: '科目代码不能为空', trigger: 'blur' },
    { max: 50, message: '科目代码长度不能超过50个字符', trigger: 'blur' }
  ],
  subjectType: [
    { required: true, message: '科目类型不能为空', trigger: 'change' },
    { max: 50, message: '科目类型长度不能超过50个字符', trigger: 'blur' }
  ],
  subjectWeight: [
    { required: true, message: '科目权重不能为空', trigger: 'blur' },
    { type: 'number', min: 0.01, max: 1, message: '科目权重必须在0.01-1之间', trigger: 'blur' }
  ],
  passingScore: [
    { required: true, message: '合格分数不能为空', trigger: 'blur' },
    { type: 'number', min: 0, max: 999.99, message: '合格分数必须在0-999.99之间', trigger: 'blur' }
  ],
  maxScore: [
    { required: true, message: '满分不能为空', trigger: 'blur' },
    { type: 'number', min: 0.01, max: 999.99, message: '满分必须在0.01-999.99之间', trigger: 'blur' }
  ],
  examLocation: [
    { max: 200, message: '考试地点长度不能超过200个字符', trigger: 'blur' }
  ]
})

/** 科目类型变化处理 */
const handleSubjectTypeChange = (value: string) => {
  if (value === 'comprehensive') {
    // 如果是综合评价，设置默认权重为0.5（表示50%）
    formData.value.subjectWeight = 0.5
  } else {
    // 如果不是综合评价，设置权重为1（后端要求必须大于0）
    formData.value.subjectWeight = 1.0
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      const data = await getSubject(id)
      Object.assign(formData.value, data)
    } catch (error) {
      console.error('获取科目详情失败:', error)
      ElMessage.error('获取科目详情失败')
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交表单 */
const submitForm = async () => {
  const elForm = formRef.value
  if (!elForm) return
  const valid = await elForm.validate()
  if (!valid) return
  formLoading.value = true
  try {
    const data = formData.value
    if (data.id) {
      await updateSubject(data)
      ElMessage.success('修改成功')
    } else {
      await createSubject(data)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planId: undefined,
    subjectName: '',
    subjectCode: '',
    subjectType: 'theory',
    subjectWeight: 1.0,
    passingScore: 60.0,
    maxScore: 100.0,
    examDuration: 120,
    examLocation: '',
    subjectDescription: ''
  }
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

/** 获取计划列表 */
const loadPlanList = async () => {
  try {
    // 获取所有状态的计划
    const allPlans = await Promise.all([
      getPlanListByStatus(0), // 草稿
      getPlanListByStatus(1), // 已提交
      getPlanListByStatus(2), // 已审批
      getPlanListByStatus(3), // 已发布
      getPlanListByStatus(4), // 进行中
      getPlanListByStatus(5)  // 已完成
    ])
    planList.value = allPlans.flat()
  } catch (error) {
    console.error('获取计划列表失败:', error)
    planList.value = []
  }
}

/** 组件挂载时加载计划列表 */
onMounted(() => {
  loadPlanList()
})

defineExpose({ open })
</script>
